<template>
  <el-dialog
  title="编辑实验数据"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="80%">
  <div class="personal">
    <el-row :gutter="20">
        <el-col :span="24">
          <el-card>
            <div id="J_chartBarBox" class="chart-box">
              <p class="part-title" style="margin-top: 5px;">实验数据</p>
                <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormEdit()" label-width="80px">
                  <el-form-item label="实验名称" prop="experimentName" style="width: 300px;">
                    <el-input v-model="dataForm.experimentName" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="实验描述" prop="experimentDesc" style="width: 300px;">
                    <el-input v-model="dataForm.experimentDesc" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="所属对象" prop="belong" style="width: 300px;">
                    <el-input v-model="dataForm.belong" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="可选人数" prop="allNumber" style="width: 300px;">
                    <el-input v-model="dataForm.allNumber" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker v-model="dataForm.startTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="结束时间" prop="endTime" >
                     <el-date-picker v-model="dataForm.endTime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss">
                     </el-date-picker>
                  </el-form-item>
                  <el-form-item  label="实验资料" prop="experimentData" style="width: 400px;" >
                      <a :href="dataForm.experimentData" v-if="disabled" >
                        <el-tag>资料下载</el-tag>
                      </a>
                      <el-button type="primary" @click="tagClose()" size="mini" v-if="disabled">删除</el-button>
                    <el-upload
                    v-if="!disabled"
                      class="upload-demo"
                      :on-success="handleAvatarSuccess"
                      :action="saveImg()"
                      :on-preview="handlePreview"
                      :on-remove="handleRemove"
                      :file-list="fileList">
                      <el-button size="small" type="primary">点击上传资料</el-button>
                    </el-upload>
                  </el-form-item>
                  <el-form-item label="实验平台" prop="experimentPlatform" style="width: 300px;">
                    <el-input v-model="dataForm.experimentPlatform" clearable></el-input>
                  </el-form-item>
                  <el-form-item label="实验要求" prop="experimentDemand" style="width: 600px;">
                    <el-input  type="textarea" :rows="5" v-model="dataForm.experimentDemand"></el-input>
                  </el-form-item>
                  <el-form-item label="报告要求" prop="workFile"style="width: 600px;">
                    <el-input type="textarea" :rows="5" v-model="dataForm.workFile"></el-input>
                  </el-form-item>
                  <el-form-item label="算法介绍" prop="fun">
                    <UEditor :config=config ref="ueditor" style="z-index: 99;"></UEditor>
                  </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer" style="margin-left: 45%;">
                  <el-button plain size="mini" type="success" @click="dataFormSave()" >保存</el-button>
                  <el-button plain size="mini"  type="danger" @click="dataFormReset()" >重置</el-button>
                  <el-button plain size="mini"  @click="dataFormCancel()" >取消</el-button>
                </span>
            </div>
          </el-card>
        </el-col>
      </el-row>
  </div>
  </el-dialog>
</template>

<script>
  /* eslint-disable */
  import { isEmail, isMobile } from '@/utils/validate'
  import UEditor from '../../compont/ueditor/ueditor.vue'

  export default {
    components: {UEditor},
    data () {
      var validateEmail = (rule, value, callback) => {
        if (!isEmail(value)) {
          callback(new Error('邮箱格式错误'))
        } else {
          callback()
        }
      }
      var validateMobile = (rule, value, callback) => {
        if (!isMobile(value)) {
          callback(new Error('手机号格式错误'))
        } else {
          callback()
        }
      }
      return {
        visible: false,
        disabled: true,
        uploadImageVisible: false,
        flag: true,
        dataForm: {
          experimentName: '',
          experimentDesc: '',
          belong: '',
          allNumber: '',
          startTime: '',
          endTime: '',
          experimentDemand: '',
          workFile: '',
          experimentData: '',
          experimentPlatform: '',
          fun: ''
        },
        config: {
            //可以在此处定义工具栏的内容
            toolbars: [[
                'fullscreen', 'source', '|', 'undo', 'redo', '|',
                'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
                'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
                'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
                'directionalityltr', 'directionalityrtl', 'indent', '|',
                'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
                'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
                , 'insertimage', 'emotion', 'insertvideo', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
                'horizontal', 'date', 'time', 'spechars', 'wordimage', '|',
                'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|',
                , 'preview', 'searchreplace', 'help'
            ]],
            autoHeightEnabled: false,
            autoFloatEnabled: true,
            initialContent:'',   //初始化编辑器的内容,也可以通过textarea/script给值，看官网例子
            autoClearinitialContent:false, //是否自动清除编辑器初始内容，注意：如果focus属性设置为true,这个也为真，那么编辑器一上来就会触发导致初始化的内容看不到了
            initialFrameWidth: null,
            initialFrameHeight: 450,
            BaseUrl: '',
            UEDITOR_HOME_URL: 'static/ueditor/'
          },
        fileList: [],
        files:[],
        dataRule: {
          experimentName: [
            { required: true, message: '实验名称不能为空', trigger: 'blur' }
          ],
          belong: [
            { required: true, message: '所属对象不能为空', trigger: 'blur' }
          ],
          allNumber: [
            { required: true, message: '可选人数不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    computed: {
      id: {
        get () { return this.$store.state.user.id },
        set (val) { this.$store.commit('user/updateId', val) }
      },
      account: {
        get () { return this.$store.state.user.account },
        set (val) { this.$store.commit('user/updateAccount', val) }
      },
      avatar: {
        get () { return this.$store.state.user.avatar },
        set (val) { this.$store.commit('user/updateAvatar', val) }
      },
      fun: {
        get () { return this.$store.state.user.fun },
        set (val) { this.$store.commit('user/updateFun', val) }
      }
    },
    methods: {
      init (uuid) {
        this.$store.commit('user/updateFun', "")
        console.log("this.$store.state.user.fun",this.$store.state.user.fun)
        this.visible = true
        this.uuid = uuid || 0
        this.fileList = []
        disabled: true
        this.dataFormSelect(this.uuid)
      },
      saveImg(){
        return this.$http.adornUrl('/file/image');
      },
      handleRemove(file, fileList) {
        fileList.push(file);
      },
      handlePreview(file) {
        fileList.remove(file)
      },
      handleAvatarSuccess(response) {
        if (response.success) {
          this.files.push(response.data)
        }else{
          this.$message.error(response.message)
        }
      },
      setContent: function(){
        this.$refs.ueditor.setUEContent();
      },
       //获取文档内容
      getContent: function(){
        let content = this.$refs.ueditor.getUEContent();
        console.log(content);
        this.dataForm.fun = content;
      },
      tagClose () {
        this.disabled = false
        this.dataForm.experimentData = ''
      },
      // 查询
      dataFormSelect (uuid) {
        this.$http({
          url: this.$http.adornUrl('/course/queryExperimentsAllByUuId'),
          method: 'get',
          params: this.$http.adornParams({
            'uuid': uuid
          })
        }).then(({data}) => {
          if (data.success) {
           this.dataForm = data.data
           if(this.dataForm.experimentData ==''|| this.dataForm.experimentData == undefined ){
             this.disabled = false
           }
           console.log("this.dataForm.experimentData,this.dataForm.disabled",this.dataForm.experimentData + this.disabled)
           this.$store.commit('user/updateFun', this.dataForm.fun)
           this.setContent()
          } else {
            this.$store.commit('user/updateFun', "")
            this.$message.error(data.message)
          }
        })
      },
      dataFormCancel(){
        this.visible = false
      },
      dataFormReset(){
        this.disabled = true
        this.dataFormSelect (this.uuid)
        this.$message("表单已复原")
      },
      // 表单提交
      dataFormSave () {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
             let content = this.$refs.ueditor.getUEContent();
             this.dataForm.fun = content;
             if(this.files == undefined || this.files == null ||  this.files.length == 0){
               this.flag = false
             }
             this.dataForm.experimentData = this.flag ? this.files[0] : this.dataForm.experimentData
             console.log("this.flag",this.flag)
              console.log("this.files[0]",this.files[0])
             console.log("this.dataForm.experimentData",this.dataForm.experimentData)
            this.$http({
              url: this.$http.adornUrl('/course/editExperimentAll'),
              method: 'post',
              data: this.$http.adornData({
                'uuid': this.uuid,
                'updateBy': this.account,
                'experimentName': this.dataForm.experimentName,
                'experimentDesc': this.dataForm.experimentDesc,
                'belong': this.dataForm.belong,
                'allNumber': this.dataForm.allNumber,
                'startTime': this.dataForm.startTime,
                'endTime': this.dataForm.endTime,
                'experimentDemand': this.dataForm.experimentDemand,
                'workFile': this.dataForm.workFile,
                'experimentData': this.dataForm.experimentData,
                'experimentPlatform': this.dataForm.experimentPlatform,
                'fun': this.dataForm.fun
              })
            }).then(({data}) => {
              if (data.success) {
                this.$message({
                  message: '数据保存成功!',
                  type: 'success'
               });
               this.fileList = []
               this.files = []
               this.visible = false
               this.flag = true
               this.disabled = true
               this.$emit('refreshDataList')
              } else {
                this.$message.error(data.message)
              }
            })
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .personal {
    > .el-row {
      margin-top: -10px;
      margin-bottom: -10px;
      .el-col {
        padding-top: 10px;
        padding-bottom: 10px;
      }
    }
    .chart-box {
      min-height: 400px;
    }
    .info {
      font-size: 16px;
      margin-bottom: 20px;
    }
    .item_bock {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height:94px;
      width: 300px;
      padding:0px 24px 0px 38px;
      border-bottom: 1px solid #f7f7f7;
      background: #fff;
    }
    .head_p {
      height:132px;
    }
    .head_img{
      height: 90px;
    }
    .head_img img{
      width:90px;
      height:90px;
      border-radius:50px
    }
    .account {
      font-size: 16px;
      margin-left: 50px;
    }
  }
  .part-title {
      margin: 20px 0;
      color: #000;
      padding-left: 1em;
      font-size: 16px;
      position: relative;
      display: inline-block;
      width: 100%;
  }
  .part-title:before{
    content: "";
    position: absolute;
    left: 0;
    top: 4px;
    width: 3px;
    height: 1em;
    background-color: #4976e8;
  }
  .el-button--primary {
      color: #fff;
      background-color: #273471 !important;
      border-color: #273471 !important;
  }
</style>
